import nProgress from "nprogress";
import { DEFAULT_HOME_PATH } from "../config";
import { accessRoutes, coreRouteNames } from "./routes";
import { useThemeStore } from "@/stores/modules/theme.js";
import { useTabBarStore } from "@/stores/modules/tab-bar";
import { useUserStore } from "@/stores/modules/user";
import { useAccessStore } from "@/stores/modules/access";

import { generateAccess } from "./access";
/**
 * 通用守卫
 */

function setupCommonGuards(router) {
  router.beforeEach(async (to, from) => {
    // 页面加载进度条
    const themeStore = useThemeStore();
    const tabBarStore = useTabBarStore();
    if (themeStore.nProgressShow) {
      nProgress.start();
    }
    tabBarStore.updateTabList(to);
    return true;
  });
  router.afterEach(async (to, from) => {
    nProgress.done();
  });
}

/**
 * 权限访问守卫配置
 * @param router
 */
function setupAccessGuard(router) {
  router.beforeEach(async (to, from) => {
    const accessStore = useAccessStore();
    const userStore = useUserStore();

  
    // 基本路由 不需要进入权限拦截
    if (coreRouteNames.includes(to.name)) {
      if (to.path == "/login" && accessStore.accessToken) {
        return decodeURIComponent(to.query?.redirect || DEFAULT_HOME_PATH);
      }
      return true;
    }

    // accessToken 检查
    // if (!accessStore.accessToken) {
    //   // 忽略权限访问权限
    //   if (to.meta.ignoreAccess) {
    //     return true;
    //   }

    //   // // 没有访问权限 跳转登录
    //   // if (to.fullPath != "/login") {
    //   //   return {
    //   //     path: "/login",
    //   //     query:
    //   //       to.fullPath == DEFAULT_HOME_PATH
    //   //         ? {}
    //   //         : {
    //   //             redirect: encodeURIComponent(to.fullPath)
    //   //           },
    //   //     replace: true
    //   //   };
    //   // }
    //   return to;
    // }

    // 是否已经生成过动态路由
    if (accessStore.isAccessChecked) {
      return true;
    }

    const userInfo = await userStore.getUserInfoAction();
    const userRoles = userInfo.roleCode;

    const { accessibleMenus, accessibleRoutes } = await generateAccess({
      roles: userRoles,
      router,
      // 则会在菜单中显示，但是访问会被重定向到403
      routes: accessRoutes
    });
    // console.log(accessibleRoutes);
    // 保存菜单信息和路由信息
    accessStore.setAccessMenus(accessibleMenus);
    accessStore.setAccessRoutes(accessibleRoutes);
    accessStore.setIsAccessChecked(true);
    const redirectPath =
      from.query.redirect ??
      (to.path === DEFAULT_HOME_PATH
        ? userInfo.homePath || DEFAULT_HOME_PATH
        : to.fullPath);
    return {
      ...router.resolve(decodeURIComponent(redirectPath)),
      replace: true
    };
  });
}

/**
 * 路由守卫
 * @param router
 */

function createRouterGuard(router) {
  setupCommonGuards(router);
  setupAccessGuard(router);
}

export { createRouterGuard };
 